package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/setting"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"log"
	"strconv"
)

type System struct {
	Base
}

// Setting 系统设置
func (s *System) Setting(c *gin.Context) {
	data := make(map[string]interface{})

	response.HTML(c, "system/setting", data)
}

// SettingList 系统设置
func (s *System) SettingList(c *gin.Context) {
	data := make(map[string]interface{})

	data["rows"] = service.System.GetSystem(1)

	response.Success(c, data)
}

// SettingUpdate 修改系统设置
func (s *System) SettingUpdate(c *gin.Context) {
	system := &model.System{}

	if err := c.ShouldBind(&system); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	systemId := strconv.Itoa(system.Id)
	err := service.System.Update(systemId, system)

	if err != nil {
		logrus.Error("修改失败： ", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, system)
}

// SettingUpdateOld 修改系统设置
func (s *System) SettingUpdateOld(c *gin.Context) {
	var siteMap setting.SiteMap

	if err := c.ShouldBind(&siteMap); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	viper.Set("site.domain", siteMap.Domain)
	viper.Set("site.title", siteMap.Title)
	viper.Set("site.keyword", siteMap.Keyword)
	viper.Set("site.description", siteMap.Description)
	viper.Set("site.email", siteMap.Email)
	viper.Set("site.contact", siteMap.Contact)
	viper.Set("site.company", siteMap.Company)
	viper.Set("site.phone", siteMap.Phone)
	viper.Set("site.icp", siteMap.Icp)
	viper.Set("site.address", siteMap.Address)
	viper.Set("site.tpl", siteMap.Tpl)

	// ini.ReflectFrom(cfg, &siteMap)
	err := viper.WriteConfig()
	if err != nil {
		log.Fatal("write config failed: ", err)
		return
	}
	response.Success(c, siteMap)
}

// Bak 数据备份
func (s *System) Bak(c *gin.Context) {
	data := make(map[string]interface{})

	response.HTML(c, "system/bak", data)
}

// Restore 数据还原
func (s *System) Restore(c *gin.Context) {
	data := make(map[string]interface{})

	response.HTML(c, "system/restore", data)
}
